package com.fc.mall.decoration.link.dao;

import com.fc.mall.decoration.link.model.Link;
import com.fc.mall.mongo.util.MongoUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;

import static com.fc.mall.util.Constants.NAME;
import static com.fc.mall.util.Constants.UPDATED_AT;
import static org.springframework.data.mongodb.core.query.Criteria.where;

@Component
public class LinkRepositoryImpl implements LinkRepositoryCustom {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public Page<Link> searchLinks(String keyword, int page, int pageSize) {

        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(keyword)) {
            Criteria keywordLikeCriteria = new Criteria().orOperator(
                    where(NAME).regex(keyword, "i"));
            criteria.andOperator(keywordLikeCriteria);
        }

        return MongoUtils.getPage(mongoTemplate, Link.class, criteria, page, pageSize, Sort.by(Sort.Direction.DESC, UPDATED_AT));
    }
}
